package absc.wizard;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard;

import absc.object.SWOTObject;

public class SWOTWizard extends Wizard implements INewWizard {
	
	private SWOTWizardPage page;
	private IStructuredSelection selection;

	public SWOTWizard() {
		setWindowTitle("SWOT Analysis");
	}

	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
	}
	
	public void addPages(){
		page = new SWOTWizardPage();
		addPage(page);
		page.init(selection);
	}

	@Override
	public boolean performFinish() {
		try{
			IFolder swotFolder = page.getSWOTFolder();
			if (! swotFolder.exists())
				swotFolder.create(true, true, null);
			
			String swotName = page.getSWOTName();			
			SWOTObject swot = new SWOTObject();
			swot.createSWOT(swotName, swotFolder.getLocation().toOSString());
			
			swotFolder.refreshLocal(IResource.DEPTH_INFINITE, null);			
			IFile file = swotFolder.getFile(swotName + ".swo");
			IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file);
			
			BasicNewResourceWizard.selectAndReveal(file, PlatformUI.getWorkbench().getActiveWorkbenchWindow());
			
			return true;
		}
		catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
}
